package dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class GenericJPADAO<T> implements GenericDAO<T> {

	@PersistenceContext
	protected EntityManager em;
	private Class<T> type;

	public GenericJPADAO() {
		ParameterizedType pt = (ParameterizedType) getClass().getGenericSuperclass();
		@SuppressWarnings("unchecked")
		Class<T> typeClass = (Class<T>) pt.getActualTypeArguments()[0]; 
		type = typeClass;
	}

	@Override
	public T persist(T entity) {
		em.persist(entity);
		return entity;
	}

	@Override
	public T merge(T entity) {
		em.merge(entity);
		return entity;
	}

	@Override
	public T remove(T entity) {
		em.remove(em.contains(entity) ? entity : em.merge(entity));
		return entity;
	}
	
	@Override
	public T getEntityById(int id) {		
		Query q = em.createQuery("SELECT e FROM " + type.getName() + " e" + " WHERE e.id = " + id);		
		@SuppressWarnings("unchecked")
		T res = (T) q.getSingleResult();		
		return res;
	}

	@Override
	public List<T> findAll() {
		Query q = em.createQuery("SELECT e FROM " + type.getName() + " e");
		@SuppressWarnings("unchecked")
		List<T> list = (List<T>) q.getResultList();
		return list;
	}	

}
